package com.zwan.oam_rtc.imps;

import com.zwan.oam_rtc.bean.PnoHandlerSettings;
import com.zwan.oam_rtc.constants.Const;
import com.zwan.oam_rtc.utils.messages.MessageHead;
import com.zwan.oam_rtc.utils.messages.PID;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
public class BasicHandler implements PnoHandler  {

	protected int pno;

	protected Map<Integer, MessageWaiter> waiters = Collections
			.synchronizedMap(new HashMap<Integer, MessageWaiter>());
	protected Map<String, MessageWaiter> waitersSNID = Collections
			.synchronizedMap(new HashMap<String, MessageWaiter>());

	@Override
	public void destroy() {
		for (Iterator<MessageWaiter> iter = waiters.values().iterator(); iter
				.hasNext();) {
			MessageWaiter waiter = iter.next();
			waiter.setMessage(null);
		}
		for (Iterator<MessageWaiter> iter = waitersSNID.values().iterator(); iter
				.hasNext();) {
			MessageWaiter waiter = iter.next();
			waiter.setMessage(null);
		}
		this.waiters.clear();
		this.waitersSNID.clear();
		log.info("====waiters clean"+this.hashCode());
	}

	@Override
	public void init(int pno) {
		this.pno = pno;
	}

	protected void sendMessage(int eventid, ByteBuffer buffer) {
		sendMessage(eventid, buffer.array());
	}
	/**
	 * 所有handler都继承该方法，该方法调用调用javaImp中的SendMessage
	 * 它的参数为pno，Const.SCP_MODULE，Const.SLP_PNO，eventid，buffer（SLP类型的数据字节串）
	 * 此处的pno为handler中的pno，handler中的pno来自配置文件
	 * @param eventid 触发业务的事件号（应该是触发SCP端业务事件的号码）
	 * @param buffer 已经封装成SLPAccessMessage后生成的字节串 
	 */
	public void sendMessage(int eventid, byte[] buffer) {
		// if (pno != Const.SLP_PNO)
		JavaImp.getInstance().sendMessage(pno, Const.SCP_MODULE, Const.SLP_PNO,
				eventid, buffer);
	}

	public void sendRtcmsMessage(int eventid, byte[] buffer) {
		JavaImp.getInstance().sendMessage(pno, Const.SCP_MODULE, Const.JANUS_PNO,
				eventid, buffer);
	}

	public void sendMessage(PID reciver, int eventid, byte[] bytes) {
		JavaImp imp = JavaImp.getInstance();
		imp.sendMessage(imp.getPID(pno), reciver, eventid, bytes);
	}

//	public SLPResponse sendMessage(SLPAccessMessage msg, boolean waitFor) {
//		SLPResponse rsp = null;
//		if (!waitFor) {
//			this.sendMessage(msg.getEventid(), msg.getByteArray(JavaImp
//					.getInstance().getByteOrder(Const.SCP_MODULE)));
//		} else {
//			try {
//				MessageWaiter mw = new MessageWaiter(this);
//				rsp = mw.sendMessage(msg);
//			} catch (InterruptedException e) {
//				log.error(e);
//			}
//		}
//		return rsp;
//	}
//
//	public SLPResponse sendMessage(SLPMessage msg, boolean waitFor,
//			ByteOrder byteOrder) {
//		SLPResponse rsp = null;
//		if (!waitFor) {
//			this.sendMessage(msg.getEventid(), msg.getByteArray(byteOrder));
//		} else {
//			try {
//				MessageWaiter mw = new MessageWaiter(this);
//				rsp = mw.sendMessage(msg.getEventid(), msg);
//			} catch (InterruptedException e) {
//				log.error(e);
//			}
//		}
//		return rsp;
//	}

	/**
	 * 注册等待实例
	 */
	@Override
	public void registerWaiter(int cidIndex, MessageWaiter messageWaiter) {
		log.info("====registerWaiter cidIndex in handler:"+this.hashCode() + " waiters:" + this.waiters.hashCode());
		this.waiters.put(cidIndex, messageWaiter);
	}

	/**
	 * 注销等待实例
	 */
	@Override
	public void unRegisterWaiter(int cidIndex, MessageWaiter messageWaiter) {
		log.info("====unRegisterWaiter cidIndex in handler:"+this.hashCode() + " waiters:" + this.waiters.hashCode());
		this.waiters.remove(cidIndex);
	}

	/**
	 * 注销等待实例
	 */
	@Override
	public void unRegisterWaiter(String snid, MessageWaiter messageWaiter) {
		log.info("====registerWaiter snid in handler:"+this.hashCode() + " waiters:" + this.waitersSNID.hashCode());
		this.waitersSNID.remove(snid);
	}

	/**
	 * 注册等待实例
	 */
	@Override
	public void registerWaiter(String snid, MessageWaiter messageWaiter) {
		log.info("====unRegisterWaiter snid in handler:"+this.hashCode() + " waiters:" + this.waitersSNID.hashCode());
		this.waitersSNID.put(snid, messageWaiter);
	}

	/**
	 * 实现基本的收消息功能，如果有等待实例，则通知它
	 */
	@Override
	public void service(MessageHead header, int eventid, ByteBuffer buffer,
						ByteOrder byteOrder) {
		log.info(MessageFormat.format(
				"Recive message from {0}.{1} to {2}.{3}, eventid={4,number,#}, length={5}",
				header.getSender().getModule(), header.getSender().getPno(), JavaImp.getInstance().getModuleNo(),
				pno, eventid, buffer.limit() - buffer.position()));
//		SLPResponse response = new SLPResponse();
//		buffer.order(byteOrder);
//		buffer.rewind();
//		response.readFromBuffer(buffer);
//		service(eventid, response, byteOrder);
//		int index = response.getMsgHead().getDlgID();
//		log.debug("return dlgid:" + index);
//		MessageWaiter waiter = this.waiters.get(index);
//		if (waiter != null) {
//			this.waiters.remove(index);
//			waiter.setMessage(response);
//		}
	}

//	/**
//	 * 响应某个事件
//	 * 
//	 * @param eventid
//	 * @param rsp
//	 */
//	protected abstract void service(int eventid, SLPResponse rsp,
//			ByteOrder byteOrder);

	public PID getPID() {
		return JavaImp.getInstance().getPID(pno);
	}

	@Override
	public void init(PnoHandlerSettings pnoHandlerSettings) {
		// TODO Auto-generated method stub
		
	}
}
